package com.mstore.dao;

import java.util.List;

import org.apache.commons.lang.StringUtils;

import com.mstore.pojo.BFunction;

public class BFunctionDao extends SuperDao {

	/**
	 * 查询所有功能
	 */
	public List<Object> getAllFunction() {
		String hql = "from BFunction";
		return super.find(hql);
	}

	/**
	 * 根据id查询功能
	 */
	public Object getFunctionById(Long funcId) {
		String hql = "from BFunction where id = ?";
		List<Object> list = getObject(hql, new Object[] { funcId });
		return list.isEmpty() ? null : list.get(0);
	}

	/**
	 * 添加功能
	 */
	public void addFunction(BFunction function) {
		save(function);
	}

	/**
	 * 删除
	 */
	public void delFunction(BFunction function) {
		delete(function);
	}

	/**
	 * 修改
	 */
	public void modifyFunction(BFunction function) {
		String separate = " set ";
		StringBuilder sb = new StringBuilder();
		sb.append("update ubcenter.b_function");

		Integer level = function.getLevel();
		if (level != null) {
			sb.append(separate);
			sb.append("function_level = ");
			sb.append(level);
			separate = ", ";
		}

		String name = function.getName();
		if (StringUtils.isNotBlank(name)) {
			sb.append(separate);
			sb.append("function_name = '");
			sb.append(name);
			sb.append("'");
			separate = ", ";
		}

		String discription = function.getDiscription();
		if (StringUtils.isNotBlank(name)) {
			sb.append(separate);
			sb.append("discription = '");
			sb.append(discription);
			sb.append("'");
			separate = ", ";
		}

		sb.append("where function_id = ");
		sb.append(function.getId());

		executeUpdate(sb.toString());
	}

	/**
	 * 查询名字是否重复，排除自身
	 */
	public List<Object> getFunctionsByNameExceptSelf(String name, Long id) {
		String sql = "from BFunction where name = ? and id != ?";
		return getObject(sql, new Object[] { name, id });
	}
	
	/**
	 * 通过名字查询
	 */
	public List<Object> getFunctionsByName(String name) {
		String sql = "from BFunction where name = ?";
		return getObject(sql, new Object[] { name });
	}

}
